package com.mybatisplus.demo.android.controller;

import com.mybatisplus.demo.android.enmu.ApiResponse;
import com.mybatisplus.demo.android.enmu.ResultCode;
import com.mybatisplus.demo.android.service.HeaderFileService;
import com.mybatisplus.demo.android.util.ApiResponseUtil;
import com.mybatisplus.demo.android.util.FileUploadUtil;
import com.mybatisplus.demo.android.util.LoggerUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 头像上传接口
 * Spring Boot默认文件上传大小为2M，多文档上传中总是出现文件大小超出限度
 * 在启动类DemoApplication.class文件中配置Bean来设置文件大小
 */
@Controller
@Api(value = "头像上传接口", tags = "头像上传接口")
public class HeaderFileController {

    @Autowired
    private HeaderFileService headerFileService;


    /**
     * 单个文件上传
     *
     * @return
     */
    @ApiOperation(value = "文件上传接口", httpMethod = "POST", response = ApiResponse.class)
    @ApiResponses(value = {
            @io.swagger.annotations.ApiResponse(code = 200, message = "{\"code\":200,\"message\":\"success\",\"data\":null}"),
            @io.swagger.annotations.ApiResponse(code = 404, message = "{\"code\":404,\"message\":\"未知错误\",\"data\":null}"),
            @io.swagger.annotations.ApiResponse(code = 216, message = "{\"code\":216,\"message\":\"文件不能为空\",\"data\":null}")
    })
    @PostMapping("admin/uploadHeader")
    @ResponseBody
    public ApiResponse uploadHeader(MultipartFile file, HttpServletRequest request) {
        LoggerUtil.info(" 文件类型", HeaderFileController.class);

        String userId = request.getHeader("userId");
        ApiResponse apiResponse = new ApiResponse();
        if (!file.isEmpty()) {
            try {
                LoggerUtil.info(" 文件名 " + file.getOriginalFilename(), HeaderFileController.class);
                LoggerUtil.info(" 文件名大小 " + file.getSize(), HeaderFileController.class);
                LoggerUtil.info(" 手机号 " + userId, HeaderFileController.class);

                String fileName = file.getOriginalFilename().trim();

                byte[] bytes = file.getBytes();
                Path path = Paths.get(FileUploadUtil.saveFile("header", userId), fileName.trim());
                Files.write(path, bytes);
                LoggerUtil.info(" 图片保存地址 " + FileUploadUtil.saveFile("header", userId), HeaderFileController.class);

                String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                        .path("/file/header")
                        .path("/" + userId + "/")
                        .path(fileName)
                        .toUriString();
                LoggerUtil.info(" 图片下载地址 " + fileDownloadUri, HeaderFileController.class);

                apiResponse = headerFileService.setHeader("" + file.getSize(), userId, fileDownloadUri);

            } catch (FileNotFoundException e) {
                apiResponse.setResultCode(ResultCode.UNKNOW_ERROR);
                apiResponse.setMessage("FileNotFoundException");
                e.printStackTrace();
            } catch (IOException e) {
                apiResponse.setResultCode(ResultCode.UNKNOW_ERROR);
                apiResponse.setMessage("IOException");
                e.printStackTrace();
            }

        } else {
            apiResponse.setResultCode(ResultCode.PARAM_ERROR);
            apiResponse.setMessage("file is null");
        }


        return ApiResponseUtil.getResult(apiResponse);
    }


    @GetMapping("/downloadFile/{type}/{userId}/{fileName:.+}")
    @ResponseBody
    public String downloadFile(@PathVariable String type, @PathVariable String userId, @PathVariable String fileName, HttpServletResponse response) {
        // Load file as Resource
        String newPath = FileUploadUtil.path + "/" + type + "/" + userId + "/" + fileName;
        LoggerUtil.info(" 图片下载 " + newPath, HeaderFileController.class);
        if (fileName != null) {
            //设置文件路径
            File file = new File(newPath);
            if (file.exists()) {
                response.setContentType("application/octet-stream");//告诉浏览器输出内容为流
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                String len = String.valueOf(file.length());
                response.setHeader("Content-Length", len);//设置内容长度
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    fis.close();
                    bis.close();
                    LoggerUtil.info(" 图片下载成功 " + newPath, HeaderFileController.class);
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                    LoggerUtil.error(" 图片下载异常 " + newPath + "/Exception/" + e.getMessage(), HeaderFileController.class);
                }
            }
        }

        return "下载失败";
    }
}
